<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>学生信息表单验证</title>
    <!-- 引入Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
        .error-message {
            color: #dc3545;
            font-size: 0.875rem;
            margin-top: 0.25rem;
            display: none;
        }

        .form-control.is-invalid+.error-message {
            display: block;
        }

        .form-select.is-invalid+.error-message {
            display: block;
        }

        .container {
            max-width: 800px;
        }

        .form-header {
            background-color: #f8f9fa;
            padding: 20px;
            border-radius: 5px;
            margin-bottom: 20px;
        }
    </style>
</head>

<body>
    <div class="container mt-5">
        <div class="form-header text-center">
            <h2>学生信息登记表</h2>
            <p class="text-muted">请填写以下信息并提交</p>
        </div>

        <form id="studentForm" class="needs-validation" novalidate>
            <!-- 姓名 -->
            <div class="mb-3">
                <label for="name" class="form-label">姓名 <span class="text-danger">*</span></label>
                <input type="text" class="form-control" id="name" name="name" required>
                <div class="error-message" id="nameError"></div>
            </div>

            <!-- 年龄 -->
            <div class="mb-3">
                <label for="age" class="form-label">年龄 <span class="text-danger">*</span></label>
                <input type="number" class="form-control" id="age" name="age" min="0" max="100" required>
                <div class="error-message" id="ageError"></div>
            </div>

            <!-- 性别 -->
            <div class="mb-3">
                <label for="gender" class="form-label">性别 <span class="text-danger">*</span></label>
                <select class="form-select" id="gender" name="gender" required>
                    <option value="" selected disabled>请选择性别</option>
                    <option value="男">男</option>
                    <option value="女">女</option>
                </select>
                <div class="error-message" id="genderError"></div>
            </div>

            <!-- 爱好 -->
            <div class="mb-3">
                <label for="hobby" class="form-label">爱好 <span class="text-danger">*</span></label>
                <input type="text" class="form-control" id="hobby" name="hobby" required>
                <div class="error-message" id="hobbyError"></div>
            </div>

            <!-- 邮箱 -->
            <div class="mb-3">
                <label for="email" class="form-label">邮箱 <span class="text-danger">*</span></label>
                <input type="email" class="form-control" id="email" name="email" required>
                <div class="error-message" id="emailError"></div>
            </div>

            <!-- 电话 -->
            <div class="mb-3">
                <label for="phone" class="form-label">电话 <span class="text-danger">*</span></label>
                <input type="tel" class="form-control" id="phone" name="phone" required>
                <div class="error-message" id="phoneError"></div>
            </div>

            <!-- 地址 -->
            <div class="mb-3">
                <label for="address" class="form-label">地址 <span class="text-danger">*</span></label>
                <textarea class="form-control" id="address" name="address" rows="3" required></textarea>
                <div class="error-message" id="addressError"></div>
            </div>

            <!-- 提交按钮 -->
            <div class="d-grid gap-2 d-md-flex justify-content-md-end mt-4">
                <button type="reset" class="btn btn-secondary me-md-2">重置</button>
                <button type="submit" class="btn btn-primary">登入</button>
            </div>

            <!-- 表单级错误提示 -->
            <div class="alert alert-danger mt-3" id="formError" style="display: none;"></div>
        </form>
    </div>

    <!-- 引入Bootstrap 5 JS 和 Popper.js -->
    <script src="https://cdn.jsdelivr.net/npm/@popperjs/core@2.11.6/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/js/bootstrap.min.js"></script>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const form = document.getElementById('studentForm');
            const formFields = {
                name: document.getElementById('name'),
                age: document.getElementById('age'),
                gender: document.getElementById('gender'),
                hobby: document.getElementById('hobby'),
                email: document.getElementById('email'),
                phone: document.getElementById('phone'),
                address: document.getElementById('address')
            };

            const errorElements = {
                name: document.getElementById('nameError'),
                age: document.getElementById('ageError'),
                gender: document.getElementById('genderError'),
                hobby: document.getElementById('hobbyError'),
                email: document.getElementById('emailError'),
                phone: document.getElementById('phoneError'),
                address: document.getElementById('addressError'),
                form: document.getElementById('formError')
            };

            // 验证规则
            const validators = {
                name: function (value) {
                    if (!value) return '姓名不能为空';
                    if (value.length > 4) return '姓名长度不能超过4个字';
                    if (/\d/.test(value)) return '姓名不能包含数字';
                    return '';
                },
                age: function (value) {
                    if (!value) return '年龄不能为空';
                    const age = parseInt(value);
                    if (isNaN(age)) return '年龄必须是数字';
                    if (age < 0 || age > 100) return '年龄必须在0-100之间';
                    return '';
                },
                gender: function (value) {
                    if (!value) return '请选择性别';
                    if (value !== '男' && value !== '女') return '性别必须是男或女';
                    return '';
                },
                hobby: function (value) {
                    if (!value) return '爱好不能为空';
                    return '';
                },
                email: function (value) {
                    if (!value) return '邮箱不能为空';
                    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                    if (!emailRegex.test(value)) return '请输入有效的邮箱地址';
                    return '';
                },
                phone: function (value) {
                    if (!value) return '电话不能为空';
                    if (!/^\d+$/.test(value)) return '电话只能包含数字';
                    if (value.length > 11) return '电话不能超过11位';
                    return '';
                },
                address: function (value) {
                    if (!value) return '地址不能为空';
                    return '';
                }
            };

            // 验证单个字段
            function validateField(fieldName, showError = true) {
                const field = formFields[fieldName];
                const errorElement = errorElements[fieldName];
                const value = field.value.trim();
                const errorMessage = validators[fieldName](value);

                if (errorMessage) {
                    if (showError) {
                        field.classList.add('is-invalid');
                        field.classList.remove('is-valid');
                        errorElement.textContent = errorMessage;
                    }
                    return false;
                } else {
                    field.classList.remove('is-invalid');
                    field.classList.add('is-valid');
                    errorElement.textContent = '';
                    return true;
                }
            }

            // 验证所有字段
            function validateForm() {
                let isValid = true;

                // 清除表单级错误
                errorElements.form.style.display = 'none';

                // 验证每个字段
                for (const fieldName in formFields) {
                    if (!validateField(fieldName)) {
                        isValid = false;
                    }
                }

                return isValid;
            }

            // 保存数据到localStorage
            function saveFormData() {
                const formData = {};
                for (const fieldName in formFields) {
                    formData[fieldName] = formFields[fieldName].value.trim();
                }

                // 获取现有学生数据或创建新数组
                let students = JSON.parse(localStorage.getItem('students') || '[]');
                students.push(formData);

                // 保存回localStorage
                localStorage.setItem('students', JSON.stringify(students));
            }

            // 添加实时验证
            for (const fieldName in formFields) {
                const field = formFields[fieldName];

                // 失去焦点时验证
                field.addEventListener('blur', function () {
                    validateField(fieldName);
                });

                // 输入时验证（延迟执行，提高性能）
                field.addEventListener('input', function () {
                    if (field.classList.contains('is-invalid')) {
                        setTimeout(() => validateField(fieldName), 500);
                    }
                });
            }

            // 表单提交处理
            form.addEventListener('submit', function (event) {
                event.preventDefault();

                if (validateForm()) {
                    try {
                        // 保存数据
                        saveFormData();

                        // 显示成功消息
                        alert('信息验证通过，即将跳转到学校官网！');

                        // 跳转到学校官网
                        window.location.href = 'https://www.jxcia.com/';
                    } catch (error) {
                        // 显示错误
                        errorElements.form.textContent = '保存数据时出错: ' + error.message;
                        errorElements.form.style.display = 'block';
                    }
                } else {
                    // 显示表单级错误
                    errorElements.form.textContent = '请修正表单中的错误后再提交';
                    errorElements.form.style.display = 'block';

                    // 滚动到第一个错误字段
                    const firstInvalidField = document.querySelector('.is-invalid');
                    if (firstInvalidField) {
                        firstInvalidField.focus();
                    }
                }
            });

            // 表单重置处理
            form.addEventListener('reset', function () {
                // 清除所有验证状态和错误消息
                for (const fieldName in formFields) {
                    const field = formFields[fieldName];
                    field.classList.remove('is-invalid', 'is-valid');
                    errorElements[fieldName].textContent = '';
                }

                // 清除表单级错误
                errorElements.form.style.display = 'none';
            });
        });
    </script>
</body>

</html>